package cn.anc.aonicardv.widget;

import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.StyleRes;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import cn.anc.aonicardv.Constant;
import cn.anc.aonicardv.MyApplication;
import cn.anc.aonicardv.R;
import cn.anc.aonicardv.bean.FileBean;
import cn.anc.aonicardv.bean.PhotoBean;
import cn.anc.aonicardv.event.PreviewSharePhotoEvent;
import cn.anc.aonicardv.module.adpter.listener.OnRecorderAlbumCancelDownloadClickListener;
import cn.anc.aonicardv.module.adpter.recorder.RecorderDownloadAdapter;
import cn.anc.aonicardv.net.download.DownLoadCallBack;
import cn.anc.aonicardv.net.download.DownLoadManager;
import cn.anc.aonicardv.util.DataClearManager;
import cn.anc.aonicardv.util.LogUtil;
import cn.anc.httpcontrolutil.CarControl;
import cn.anc.httpcontrolutil.cache.CacheManager;
import rx.Subscription;

/**
 * Created by yangdai on 2017/12/14.
 */

public abstract class RecorderAlbumDownloadDialog extends Dialog implements OnRecorderAlbumCancelDownloadClickListener, View.OnClickListener, DialogInterface.OnShowListener {

    public static final int TYPE_PHOTO = 0;
    public static final int TYPE_VIDEO = 1;
    public static final int TYPE_URGENT_VIDEO = 2;
    private TextView downloadTypeTv;
    private TextView cancelAllDownloadTv;
    private RecyclerView downloadRv;
    private List<FileBean> mDownloadList;
    private RecorderAlbumDownloadCallBack recorderAlbumDownloadCallBack;
    private RecorderDownloadAdapter recorderDownloadAdapter;
    private boolean isSharing;
    private int mType;
    private Subscription sub;
    private int completeDownloadCount;
    private int downloadTotalCount;
    private Context mContext;
    private  int downloadType ;


    public RecorderAlbumDownloadDialog(@NonNull Context context, @StyleRes int themeResId, int type, boolean isSharing, List<? extends FileBean> downloadList) {
        super(context, themeResId);
        mContext = context;
        init(type, isSharing, downloadList);
    }

    private void init(int type, boolean isSharing, List<? extends FileBean> downloadList) {
        this.isSharing = isSharing;
        this.mType = type;
        if (mType == TYPE_PHOTO) {
            downloadType = Constant.DOWNLOAD.TYPE_PHOTO;
        } else if (mType == TYPE_VIDEO) {
            downloadType = Constant.DOWNLOAD.TYPE_REC;
        } else {
            downloadType = Constant.DOWNLOAD.TYPE_EVENT;
        }


        downloadTotalCount = downloadList.size();
        setContentView(R.layout.dialog_recorder_album_download);
        setCancelable(false);
        downloadTypeTv = findViewById(R.id.tv_download_type);
        cancelAllDownloadTv = findViewById(R.id.tv_cancel_all_download);
        downloadRv = findViewById(R.id.rv_download);
        mDownloadList = new ArrayList<>();
        mDownloadList.addAll(downloadList);
        recorderAlbumDownloadCallBack = new RecorderAlbumDownloadCallBack();
        recorderDownloadAdapter = new RecorderDownloadAdapter(mDownloadList, this);
        downloadRv.setLayoutManager(new LinearLayoutManager(getContext()));
        downloadRv.setAdapter(recorderDownloadAdapter);
        cancelAllDownloadTv.setOnClickListener(this);
        setOnShowListener(this);
        setDownloadTitle(type, completeDownloadCount, downloadTotalCount);
    }

    private void setDownloadTitle(int type, int completeDownloadCount, int downloadTotalCount) {
        String title;
        if (type == TYPE_PHOTO) {
            title = getContext().getString(R.string.recorder_album_photo_download);
        } else if (type == TYPE_VIDEO) {
            title = getContext().getString(R.string.recorder_album_video_download);

        } else {
            title = getContext().getString(R.string.recorder_album_urgent_video_download);
        }
        title += " (" + completeDownloadCount + "/" + downloadTotalCount + ")";
        downloadTypeTv.setText(title);
    }

    private void download() {
        if (mDownloadList.get(0).getDownloadStatus() != FileBean.DownLoadStatus.WAITING_DOWNLOADED)
            return;
        mDownloadList.get(0).setDownloadStatus(FileBean.DownLoadStatus.DOWNLOADING);
        if (!CacheManager.checkCacheExist(mDownloadList.get(0).getPath())) {
            List<Integer> integers = new ArrayList<>();
            integers.add(0);
            if (mType == TYPE_PHOTO) {
                CarControl.doGetPhotoThumbnail(mDownloadList, integers, cardvThumbnailCallback);
            }
            else {
                CarControl.doGetVideoThumbnail(mDownloadList, integers, cardvThumbnailCallback);
            }
        }
        else {
            sub = DownLoadManager.getInstance().download(mDownloadList.get(0).getPath(), DownLoadManager.getInstance().getDownloadPathByRemotePath(downloadType,mDownloadList.get(0).getPath()), recorderAlbumDownloadCallBack);

        }
    }

    private void downloadError(String msg) {
        if (!TextUtils.isEmpty(msg))
            Toast.makeText(MyApplication.getInstance(), msg, Toast.LENGTH_LONG).show();
        else
            Toast.makeText(MyApplication.getInstance(), getContext().getString(R.string.recorder_album_download_fail), Toast.LENGTH_LONG).show();

        for (int i = 0; i < mDownloadList.size(); i++) {
            mDownloadList.get(i).setDownloadStatus(FileBean.DownLoadStatus.NO_DOWNLOADED);
        }
        dismiss();
    }

    @Override
    public void downloadCancel(int position) {
        try {
            deleteLocalFileByPosition(position);
            if (mDownloadList.get(position).getDownloadStatus() == FileBean.DownLoadStatus.DOWNLOADING) {
                sub.unsubscribe();
            }
            mDownloadList.get(position).setDownloadStatus(FileBean.DownLoadStatus.NO_DOWNLOADED);
            mDownloadList.remove(position);
            downloadTotalCount--;
            if (mDownloadList.size() > 0) {
                setDownloadTitle(mType, completeDownloadCount, downloadTotalCount);
                recorderDownloadAdapter.notifyDataSetChanged();

                download();
            } else {
                dismiss();
            }
        }catch (Exception e){
        }

    }

    private void deleteLocalFileByPosition(int position) {

        String path = DownLoadManager.getInstance().getDownloadPathByRemotePath(downloadType,mDownloadList.get(position).getPath());
        File f = new File(path);
        if (f.exists())
            f.delete();
    }

    @Override
    public void onClick(View v) {
        downloadCancel();
    }

    private void downloadCancel() {
        deleteLocalFileByPosition(0);
        for (int i = 0; i < mDownloadList.size(); i++) {
            mDownloadList.get(i).setDownloadStatus(FileBean.DownLoadStatus.NO_DOWNLOADED);
        }
        try {
            sub.unsubscribe();
        }catch (Exception e){
        }

        dismiss();
    }

    @Override
    public void onShow(DialogInterface dialog) {
        download();
    }

    public class RecorderAlbumDownloadCallBack extends DownLoadCallBack {

        @Override
        public void onCancel() {
        }

        @Override
        public void onCompleted(String path, Uri uri) {
            completeDownloadCount++;
            setDownloadTitle(mType, completeDownloadCount, downloadTotalCount);
            CarControl.CarDvThumbnailMediaInfo carDvThumbnailMediaInfo = null;
            if (mType == TYPE_PHOTO) {
                carDvThumbnailMediaInfo = CacheManager.getMediaInfoFromExif(CacheManager.getCachePath(mDownloadList.get(0).path));
                CacheManager.saveMediaInfoToExif(carDvThumbnailMediaInfo, path);
            } else
                saveVideoInfoToDataBase(mDownloadList.get(0).getPath(), uri);
            mDownloadList.get(0).setDownloadStatus(FileBean.DownLoadStatus.COMPLETE_DOWNLOADED);
            if (!isSharing) {
                mDownloadList.remove(0);
                recorderDownloadAdapter.notifyItemRemoved(0);
                recorderDownloadAdapter.notifyItemRangeChanged(0, mDownloadList.size());
                if (mDownloadList.size() > 0) {
                    download();
                } else
                    dismiss();
            } else {
                if (mType == TYPE_PHOTO) {
                    List<PhotoBean> photoBeanList = new ArrayList<>();
                    PhotoBean photoBean = new PhotoBean();
                    photoBean.setPath(path);
                    photoBean.setFileCreateTime(carDvThumbnailMediaInfo != null ? carDvThumbnailMediaInfo.file_time : null);
                    photoBeanList.add(photoBean);
                    EventBus.getDefault().postSticky(new PreviewSharePhotoEvent(photoBeanList));
                    sharePhoto(path);
                }
                dismiss();
            }
            isSharing = false;
        }

        @Override
        public void onError(String e) {
            downloadError(e);
        }

        @Override
        public void onProgress(long fileSizeDownloaded, long totalSize) {
            if (!mDownloadList.isEmpty()) {
                RecorderDownloadAdapter.ViewHolder viewHolder = (RecorderDownloadAdapter.ViewHolder) downloadRv.findViewHolderForAdapterPosition(0);
                if (viewHolder == null)
                    return;
                int progress = (int) (fileSizeDownloaded * 100 / totalSize);
                viewHolder.thumbPiv.setProgress(progress);
                viewHolder.progressTv.setText(viewHolder.itemView.getResources().getString(R.string.recorder_album_download_progress) + " " + progress + "%/" + DataClearManager.getFormatSize(totalSize));
            }
        }
    }

    public void saveVideoInfoToDataBase(final String downloadPath, Uri uri) {
        if (uri != null) {
            LogUtil.e("llcTest","--------111888--downloadPath-:"+downloadPath);
            LogUtil.e("llcTest","--------111888--uri-:"+uri.toString());
            ContentValues c = new ContentValues();
            LogUtil.e("llcTest","--------111888--MediaStore.Video.Media.TAGS-:"+CacheManager.getMediaInfoFromExif(CacheManager.getCachePath(downloadPath)).toString());
            c.put(MediaStore.Video.Media.TAGS, CacheManager.getMediaInfoFromExif(CacheManager.getCachePath(downloadPath)).toString());
            getContext().getContentResolver().update(uri, c, null, null);
        }
    }

    CarControl.OnCardvThumbnailCallback cardvThumbnailCallback = new CarControl.OnCardvThumbnailCallback() {
        @Override
        public void OnThumbnailGetted(int index) {
            recorderDownloadAdapter.notifyItemChanged(0);
            sub = DownLoadManager.getInstance().download(mDownloadList.get(0).getPath(), DownLoadManager.getInstance().getDownloadPathByRemotePath(downloadType,mDownloadList.get(0).getPath()), recorderAlbumDownloadCallBack);
        }
    };
    public abstract void sharePhoto(String path);
}